﻿using SQLDeployAnything.Data.Files;
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SQLDeployAnything.Data.Commands
{
    public class CreateEnvironment : ICommand
    {
        private Connections _connections;

        internal CreateEnvironment(Connections connectionsFile)
        {
            if (connectionsFile == null)
                throw new ArgumentNullException("connectionsFile");
            _connections = connectionsFile;
        }

        public bool CanExecute(object parameter)
        {
            try
            {
                if (!(parameter is string))
                    return false;
                string name = (string)parameter;

                if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
                    return false;

                foreach (Environment.Environment env in _connections.Environments)
                {
                    if (name.Equals(env.Name))
                        return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
            finally
            {
                //EventHandler handler = CanExecuteChanged;
                //if (handler != null)
                //    handler(this, new PropertyChangedEventArgs("CanExecute"));
            }
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        
        public void Execute(object parameter)
        {
            if (!(parameter is string))
                throw new ArgumentException();

            string name = (string)parameter;

            if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
                throw new ArgumentException();

            foreach (Environment.Environment env in _connections.Environments)
            {
                if (name.Equals(env.Name))
                    throw new ArgumentException();
            }
            this._connections.CreateEnvironment(name);
        }
    }
}
